<?php
namespace app\vedio\controller;
use app\home\service\DoubanService;
use QL\QueryList;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\GuzzleException;

class Search extends BaseController
{

    public function index() {
        $keyword = $this->request->get('keyword');
        $p = $this->request->get('p');
        $client = new Client(['timeout'  => 3.0,]);
        $uri = "https://m.douban.com/j/search/?q={$keyword}&t=movie&p={$p}";
        $response = $client->request('get', $uri);

        $rt = (string) $response->getBody();
        $rt = json_decode($rt, true);

        $ql = QueryList::getInstance();
        $films = $ql->setHtml($rt['html'])->rules([
            'id'    => ['li > a', 'href'],
            'title' => ['li > a .subject-title', 'text'],
            'cover' => ['li > a > img', 'src'],
            'rate'  => ['li > a > .subject-info > p > span:last-child', 'html'],
        ])->query()->getData(function ($item){
            preg_match('/\d{3,}/', $item['id'],$match_id);
            $item['id'] = array_pop($match_id);
            if (!is_numeric($item['rate'])) {
                $item['rate'] = 0;
            }
            return $item;
        })->all();
        return $this->_returnJson($films);
    }

    public function index_v()
    {
        $keyword = $this->request->get('keyword');
        $doubanService = new DoubanService();
        $suggestApi = str_replace('{q}', $keyword, DoubanService::API_SEARCH_SUGGEST);

        $suggestResponse = $doubanService->request($suggestApi);
        $films = $doubanService->parseSearchSuggestResponse($suggestResponse);

        return $this->_returnJson($films);
    }




}
